import AmapLoader from '@amap/amap-jsapi-loader';
import { onUnmounted } from 'vue';

interface IconOptions {
  size?: [number, number];
  imageSize?: [number, number];
  imageOffset?: [number, number];
}

export const useGDMap = () => {
  let GMap: any = null;
  let map: any = null;

  // 初始化数据
  const initData = async (id: string, center: [number, number], options?: any) => {
    GMap = await loadData();
    map = new GMap.Map(id, { center, ...options });
    await setEventCompleteListener();
    return map;
  };

  // 加载数据
  const loadData = () => {
    return new Promise((resolve) => {
      AmapLoader.load({
        key: '154b0234be94e8f75e18e7ebdcde6eec',
        version: '2.0',
        plugins: ['AMap.Geolocation'],
        Loca: { version: '2.0.0' },
      }).then(async (AMap: any) => {
        resolve(AMap);
        (window as any).AMap = AMap;
      });
    });
  };

  // 地图加载完成回调
  const setEventCompleteListener = () => {
    return new Promise((resolve: any) => {
      map.on('complete', () => {
        resolve(true);
      });
    });
  };

  // 销毁地图
  const destroyMap = () => {
    if (map) map.destroy();
  };

  // 设置点覆盖物 - 单个
  const setMarker = (point: [number, number], icon?: string, offset?: [number, number]) => {
    const [lng, lat] = point;
    const [x, y] = offset || [0, 0];
    const marker = new GMap.Marker({ position: new GMap.LngLat(lng, lat), icon, offset: new GMap.Pixel(x, y) });
    map.add(marker);
  };

  const getIcon = (url: string, options?: IconOptions) => {
    const iconData: any = { image: url };

    if (options.size) iconData.size = new GMap.Size(options.size[0], options.size[1]);
    if (options.imageSize) iconData.imageSize = new GMap.Size(options.imageSize[0], options.imageSize[1]);
    if (options.imageOffset) iconData.imageOffset = new GMap.Pixel(options.imageOffset[0], options.imageOffset[1]);

    return new GMap.Icon(iconData);
  };

  onUnmounted(() => {
    destroyMap();
  });

  return { initData, destroyMap, setMarker, getIcon };
};
